#!/usr/local/bin/perl
use strict;
use warnings;

use Data::Dumper;

my $file = shift;

my $outFile = $file . ".dat";

open(FIN,$file) || die "cannot open $file $!";
my @antenna = <FIN>;
close(FIN);

my $formatVersionRGX = qr/ANTEX\sVERSION\s/;
my $pcvVersionRGX = qr/PCV\sTYPE\s\/\sREFANT/;
my $commentRGX = qr/\s+COMMENT/;
my $eohRGX = qr/END\sOF\sHEADER/;

my $startAntennaRGX = qr/START\sOF\sANTENNA/;
my $antennaTypeRGX = qr/TYPE\s\/\sSERIAL\sNO/;
my $startFreqRGX = qr/\s+(\w+)\s+START\sOF\sFREQUENCY/;
my $neuRGX = qr/\s+([.0-9]+)\s+([.0-9]+)\s+([.0-9]+)\s+NORTH\s\/\sEAST\s\/\sUP/;

my $endFreqRGX = qr/\s+(\w+)\s+END\sOF\sFREQUENCY/;
my $endAntRGX = qr/\s+END\sOF\sANTENNA/;

my $antennaFlag = 0;
my $startFlag = 0;
my $freq;
my $antenna = {};
my $antennaType;
my $endAntFlag = 0;

foreach my $line (@antenna) {
    if($line =~ $formatVersionRGX ) {
        next;
    }
    elsif($line =~ $pcvVersionRGX ) {
        next;
    }
    elsif($line =~ $commentRGX ) {
        next;
    }
    elsif($line =~ $eohRGX ) {
        next;
    }
    elsif($line =~ $startAntennaRGX ) {
        $antennaFlag = 1;
        next;
    }
    elsif($line =~ $antennaTypeRGX ) {
        $antennaType = substr $line, 0, 20;
        $antennaType =~ s/^\s+//;
        $antennaType =~ s/\s+$//;
        next;
    }
    elsif($line =~ $startFreqRGX ) {
        $freq = $1;
        $startFlag = 1;
        next;
    }
    elsif($line =~ $neuRGX ) {
        #print "North $1\n";
        #print "East  $2\n";
        #print "UP    $3\n";
        next;
    }
    elsif( $line =~ $endFreqRGX ) {
        $startFlag = 0;
    }
    elsif( $line =~ $endAntRGX ) {
        $endAntFlag = 1;
    }
    elsif( $startFlag ) {
        $line =~ s/^\s+//;
        my @values = split(/\s+/,$line);
        my $azi = shift @values ;
        $antenna->{$antennaType}{$freq}{$azi} = \@values;
    }
    
}

#print Dumper($antenna);

open(FOUT,">out_L1.txt");
print "ANtenna: $antennaType\n";
for( my $i = 0 ; $i <= 360; $i = $i + 5) {
    my $index = $i . ".0";
    my $values = $antenna->{$antennaType}{G01}{$index};
    for(my $j = 0; $j <= 90; $j = $j+5 ) {
        my $value = shift @$values; 
        print FOUT "$i $j $value\n";
    }
}
close(FOUT);

open(FOUT,">out_L2.txt");
print "ANtenna: $antennaType\n";
for( my $i = 0 ; $i <= 360; $i = $i + 5) {
    my $index = $i . ".0";
    my $values = $antenna->{$antennaType}{G02}{$index};
    for(my $j = 0; $j <= 90; $j = $j+5 ) {
        my $value = shift @$values; 
        print FOUT "$i $j $value\n";
    }
}
close(FOUT);
